package com.junchenrobot.mes.service.impl;

import com.junchenrobot.mes.client.KCClient;
import com.junchenrobot.mes.core.TaskExecutorCenter;
import com.junchenrobot.mes.core.TaskManagment;
import com.junchenrobot.mes.core.TaskScheduled;
import com.junchenrobot.mes.dao.DeviceDao;
import com.junchenrobot.mes.dao.WinderTaskDao;
import com.junchenrobot.mes.domain.PointLine;
import com.junchenrobot.mes.domain.WinderTask;
import com.junchenrobot.mes.dto.response.VehicleStatusDto;
import com.junchenrobot.mes.dto.response.VehicleStatusListDto;
import com.junchenrobot.mes.enums.ExecuteStateEnum;
import com.junchenrobot.mes.exceptions.TaskNotFoundException;
import com.junchenrobot.mes.response.BaseResponse;
import com.junchenrobot.mes.response.impl.MesResponse;
import com.junchenrobot.mes.response.impl.RcsResponse;
import com.junchenrobot.mes.service.RcsService;
import com.junchenrobot.mes.vo.param.GateResourceParam;
import com.junchenrobot.mes.vo.param.TaskStateParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class AsyncRcsServiceImpl implements RcsService {

    private final TaskExecutorCenter taskExecutorCenter;

    private final WinderTaskDao winderTaskDao;

    private final TaskManagment taskManagment;

    private final KCClient kcClient;

    private final TaskScheduled taskScheduled;

    private final DeviceDao deviceDao;

    @Autowired
    public AsyncRcsServiceImpl(TaskExecutorCenter taskExecutorCenter, WinderTaskDao winderTaskDao, KCClient kcClient,
                               TaskManagment taskManagment, TaskScheduled taskScheduled, DeviceDao deviceDao) {
        this.taskExecutorCenter = taskExecutorCenter;
        this.winderTaskDao = winderTaskDao;
        this.taskManagment = taskManagment;
        this.taskScheduled = taskScheduled;
        this.deviceDao = deviceDao;
        this.kcClient = kcClient;
    }

    @Override
    public BaseResponse taskStatus(TaskStateParam taskStateParam) {
        // 查找任务是否存在
        String taskNo = taskStateParam.getTaskNo();
        String state = taskStateParam.getState();
        WinderTask winderTask = winderTaskDao.getTask(taskNo);
        List<WinderTask> winderTaskList = winderTaskDao.listTaskConditionOne(winderTask.getTaskDeviceName(),
                ExecuteStateEnum.TASK_FINISHED.getState(), 2);
        if (Objects.isNull(winderTask)) {
            throw new TaskNotFoundException("任务未找到", taskNo);
        }
        if ("11".equals(state)) {
            return new RcsResponse().fault(taskNo + "上装任务进行中");
        }
        if ("12".equals(state)) {
            return new RcsResponse().fault(taskNo + "上装任务进行中");
        }
        if ("0".equals(state)) {
            if (winderTaskList.size() == 2){
                for (WinderTask task : winderTaskList) {
                    task.setTaskStartTime(LocalDateTime.now());
                    // 更新状态正在执行
                    task.setTaskExecuteStatus(ExecuteStateEnum.TASK_EXECUTING.getState());
                    winderTaskDao.updateTaskById(task);
                }
                return new RcsResponse().success();
            }
            winderTask.setTaskStartTime(LocalDateTime.now());
            // 更新状态正在执行
            winderTask.setTaskExecuteStatus(ExecuteStateEnum.TASK_EXECUTING.getState());
            winderTaskDao.updateTaskById(winderTask);
            return new RcsResponse().success();
        }
        // 任务是否存在
        if (!taskExecutorCenter.exist(taskNo)) {
            // 添加新的任务
            taskExecutorCenter.addTask(taskNo);
        }
        // 检查异步执行任务
        Integer result = taskExecutorCenter.checkState(taskNo, Integer.parseInt(state));
        // 未创建异步任务
        if (result == 0) {
            // 装载到位
            if ("1".equals(state)) {
                taskManagment.winderReady(taskNo);
            }
            // 动作完成
            if ("2".equals(state)) {
                taskManagment.winderPush(taskNo);
            }
            // 装载任务完成
            if ("3".equals(state)) {
                taskManagment.inputFinished(taskNo);
            }
            // 卸载到位
            if ("4".equals(state)) {
                taskManagment.transferReady(taskNo);
            }
            // 卸载完成
            if ("5".equals(state)) {
                taskManagment.transferPush(taskNo);
            }
            // 卸载完成
            if ("6".equals(state)) {
                       taskManagment.outputFinished(winderTaskList,taskNo);
            }
            // 取消任务
            if ("20".equals(state)) {
                if (winderTask.getTaskType() == 1) {//取料
                    //取消任务
                    taskManagment.cancelTask(taskNo);
                } else {
                    log.info("清空该任务");
                    for (WinderTask task : winderTaskList) {
                        taskExecutorCenter.clearStatus(task.getTaskCode());
                    }
                }
            }
            // 确定已经创建任务
            taskExecutorCenter.setStatus(taskNo, Integer.parseInt(state));
            return new RcsResponse().fault(taskNo + "上装任务进行中");
        }
        // 异步任务异常
        if (result == 3) {
            if (winderTask.getTaskType() == 1) {
                taskManagment.cancelTask(taskNo);
            }
        }
        // 正常通过
        if (result == 2) {
            if (state.equals("3")) {
                taskExecutorCenter.removeTask(taskNo);
            }
            if (state.equals("6")) {
                taskExecutorCenter.removeTask(taskNo);
            }
            return new RcsResponse().success();
        }
        return new RcsResponse().fault(taskNo + "上装任务进行中");
    }

    /**
     * 修改大门状态
     *
     * @param gateResourceParam 大门资源参数
     */
    @Override
    public BaseResponse updateGateStatus(GateResourceParam gateResourceParam) {
        String state;
        // 任务是否存在
        if (!taskExecutorCenter.exist(gateResourceParam.getResourceID())) {
            // 添加新的任务
            taskExecutorCenter.addTask(gateResourceParam.getResourceID());
        }
        // 检查异步执行任务
        Integer action = gateResourceParam.getAction();
        if (action == 1) {
            state = "8";
        } else {
            state = "9";
        }
        Integer result = taskExecutorCenter.checkState(gateResourceParam.getResourceID(), Integer.parseInt(state));
        // 未创建异步任务
        if (result == 0) {
            log.info("修改大门状态");
            //修改大门状态
            taskManagment.modifiedGate(gateResourceParam.getAction()
                    , gateResourceParam.getResourceID(), Integer.parseInt(state));
            // 确定已经创建任务
            taskExecutorCenter.setStatus(gateResourceParam.getResourceID(), Integer.parseInt(state));
            return new RcsResponse().fault(gateResourceParam.getResourceID() + "上装任务进行中");
        }
        if (result == 2) {
            taskExecutorCenter.removeTask(gateResourceParam.getResourceID());
            return new RcsResponse().success();
        }
        return new RcsResponse().fault(gateResourceParam.getResourceID() + "上装任务进行中");
    }

}
